const cache = require('memory-cache');
const request = require('superagent');
const crypto = require('crypto')
    // const url = require('url')
const appid = 'wx9259e3966574a4dd'
const secret = '19f7cc06c17d29d912ab11dd06e19060'

module.exports = function(req, res) {
    getJsApi(req).then(data => {
        res.send(data)
    })

}

/**获取token */
function getToken() {
    return new Promise((resolve, reject) => {
        let cache_token = cache.get('token');
        if (cache_token) {
            console.log(cache_token)
            resolve(cache_token);
        } else {
            resolve(saveToken());
        }
    })
}

/**保存token */
function saveToken() {
    return new Promise((resolve, reject) => {
        request
            .get('https://api.weixin.qq.com/cgi-bin/token')
            .query({
                grant_type: 'client_credential',
                appid: appid,
                secret: secret
            })
            .end(function(err, res) {
                if (res) {
                    cache.put('token', res.body.access_token, 72000 * 1000);
                    resolve(res.body.access_token)
                } else {
                    reject(err)
                }
            })
    })

}

/**获取ticket */
function getTicket() {
    let cache_ticket = cache.get('ticket');
    if (cache_ticket) {
        return cache_ticket;
    } else {
        return saveTicket();
    }
}

/**保存ticket */
function saveTicket() {
    return new Promise((resolve, reject) => {
        getToken().then((token) => {
            request
                .get('https://api.weixin.qq.com/cgi-bin/ticket/getticket')
                .query({
                    access_token: token,
                    type: 'jsapi'
                })
                .end(function(err, res) {
                    if (res) {
                        cache.put('ticket', res.body.ticket, 72000 * 1000)
                        resolve(res.body.ticket)
                    } else {
                        reject(err)
                    }
                })
        }).catch(function(err) {
            console.log(err)
        })
    })


}

// sha1加密
function sha1(str) {
    let shasum = crypto.createHash("sha1")
    shasum.update(str)
    str = shasum.digest("hex")
    return str
}

/**timestamp*/
function createTimestamp() {
    return parseInt(new Date().getTime() / 1000) + ''
}

/**noncestr*/
function createNonceStr() {
    return Math.random().toString(36).substr(2, 15)
}

/**sign and callback */
function getJsApi(req) {
    let noncestr = createNonceStr();
    let timestamp = createTimestamp();
    var url = 'req.headers.referer'

    return getTicket().then((ticket) => {
        let sortData = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        let signature = sha1(sortData);
        console.log(signature)
        return { 'appId': appid, 'timestamp': timestamp, 'nonceStr': noncestr, 'signature': signature }
    })
}